package com.desin.modle.creational.singleton;

import java.io.*;

/**
 * 单例模式
 */
public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        Thread t1 = new Thread(new T());
//        Thread t2 = new Thread(new T());
//        t1.start();
//        t2.start();
//        System.out.println("this is end");

        //通过序列化和反序列化方式违反单例模式初衷,通过在单例类中加入readResolve方法，来反射调用此方法来解决该问题
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file"));
        oos.writeObject(hungrySingleton);

        File file = new File("singleton_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        HungrySingleton singleton = (HungrySingleton)ois.readObject();

        System.out.println(hungrySingleton);
        System.out.println(singleton);
        System.out.println(hungrySingleton==singleton);
    }
}
